Day 8 - Variables
– You’re not part of this equation.
Die Hard (1988)
The Unix terminal provides variables, like many programming languages. Unfortunately, unlike
other programming languages, bash does not provide data types, and this is a very important thing
to remember. In bash, all variables are untyped, or, if you prefer, are just strings.
The assignment operator is =, so if you run
$ x=pdf
the variable x assumes the value pdf as a string. As happened with echo you can use quotes, which
are usually a good way to signal that we are dealing with a string, therefore you should. Remember
they are not strictly necessary, though, as you can find many scripts that do not use them.
$ x="pdf"
You cannot, instead, use spaces, as the line x = "pdf" would be interpreted as the execution of the
command x with two parameters = and "pdf". Weird, isn’t it? It is, but this is due to the double nature
of the terminal. It’s a command-line interface to the operating system, but it’s also a programming
language, so the two aspects sometimes clash.
As I said, variables are always strings, so
$ x=5
is not assigning the integer value 5 to x, but the string "5". This has some implications, but the most
important for the time being is that mathematical operators are slightly convoluted in bash. We will
discuss this later, however, so you don’t need to worry now. Just remember that if you type x=5+1
you are assigning x the value of the string "5+1". Facepalm moment for you, the first time you will
write this in one of your scripts.
To refer to a variable, that is, to use its value, we use the syntax ${variable}. For example